//
//  CompanySelfCheckVC.m
//  u76ho
//
//  Created by m-air-01 on 16/1/22.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "CompanySelfCheckVC.h"
#import "AnswerTableViewCell.h"

@interface CompanySelfCheckVC ()
<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,UIAlertViewDelegate>
{
    UITableView * _tableView;
    NSMutableArray * questionArr;
    NSMutableArray * answerArr;
    
    NSMutableArray * selectedArr;
    
    CompanySelfCheckOneModel * oneModel;
}
@end

@implementation CompanySelfCheckVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self main];
    self.navigationItem.title =  @"企业自检";
    
    //[self addNavgationBar];
    // Do any additional setup after loading the view.
}
-(void)main
{
    questionArr = [[NSMutableArray alloc]init];
    answerArr = [[NSMutableArray alloc]init];
    selectedArr = [[NSMutableArray alloc]init];
    
    self.view.userInteractionEnabled = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.userInteractionEnabled = YES;
    _tableView.tableFooterView = [self createtableViewFooterView];
    [_tableView registerNib:[UINib nibWithNibName:@"AnswerTableViewCell" bundle:nil] forCellReuseIdentifier:@"AnswerTableViewCell"];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self requestData];
    [self registerForKeyboardNotifications];
}
-(void)requestData
{
//    [U76HONet companyZiJianWithaction:@"" Code:[Singleton share].yqcode andDataBlock:^(CompanySelfCheckModel *model) {
//        NSLog(@"企业自检获数据成功了");
//        NSArray * arr = model.dataArr;
//        for (int i = 0; i<arr.count; i++) {
//            CompanySelfCheckOneModel * model = arr[i];
//            oneModel = model;
//            [questionArr addObject:model];
//            NSMutableArray * mArr = [[NSMutableArray alloc]init];
//            NSMutableArray * mArr2 = [[NSMutableArray alloc]init];
//            for (int i = 0; i<6; i++) {
//                [mArr addObject:model];
//                [mArr2 addObject:@"0"];
//            }
//            [answerArr addObject:mArr];
//            [selectedArr addObject:mArr2];
//        }
//        [_tableView reloadData];
//    }];
    
    [U76HONet companyZiJianWithaction:@"" Code:[Singleton share].yqcode andDataBlock:^(NSArray *arr) {
        NSLog(@"企业自检获数据成功了");
        if (arr.count == 0) {
            [self nosearch];
        }
        else
        {
            for (int i = 0; i<arr.count; i++) {
                CompanySelfCheckOneModel * model = arr[i];
                oneModel = model;
                [questionArr addObject:model];
                NSMutableArray * mArr = [[NSMutableArray alloc]init];
                NSMutableArray * mArr2 = [[NSMutableArray alloc]init];
                for (int i = 0; i<oneModel.answerArr.count; i++) {
                    [mArr addObject:model];
                    [mArr2 addObject:@"0"];
                }
                [answerArr addObject:mArr];
                [selectedArr addObject:mArr2];
            }
            [_tableView reloadData];
        }
    }];
}
-(void)nosearch
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    view.backgroundColor = UIColorFromRGB(0xf1f3f2);
    view.tag = 504;
    
    UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-98/2,SIZETO6H(120), 98, 100)];
    imgV.image = [UIImage imageNamed:@"苦脸"];
    [view addSubview:imgV];
    
    UILabel * tipLab = [[UILabel alloc]initWithFrame:CGRectMake(0, imgV.bottom+SIZETO6H(20), SCREEN_WIDTH, 20)];
    tipLab.text = @"暂时没有符合条件的内容";
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.font = [UIFont systemFontOfSize:14];
    tipLab.textColor = UIColorFromRGB(0x333944);
    [view addSubview:tipLab];
    [self.view addSubview:view];
}

-(void)subAnswerWithArr:(NSString *)arr andSuggest:(NSString *)suggest
{
    if ([self isLogin]) {
        __weak typeof(self)weakSelf = self;
        [U76HONet submitTestAnswerWithaction:@"" Code:[Singleton share].code TestId:oneModel.ids Quests:arr suggest:suggest andDataBlock:^(NSDictionary *dic) {
            NSLog(@"提交试卷成功了");
            [weakSelf performSelector:@selector(backItem:) withObject:nil afterDelay:1.0];
            //        [self.navigationController popViewControllerAnimated:YES];
        }];

    }
    
}
-(BOOL)isLogin
{
    if ([Singleton share].code) {
        NSLog(@"登录了");
        return YES;
        
    }
    else
    {
        //        NSLog(@"还没登录呢");
        //        LoginViewController * loginVC = [[LoginViewController alloc]init];
        //        [self.navigationController pushViewController:loginVC animated:NO];
        //        return NO;
        if (SYSTEM_VERSION >= 8.0) {
            UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录是否登录" preferredStyle:UIAlertControllerStyleAlert];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                LoginViewController * loginVC = [[LoginViewController alloc]init];
                UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
                nvc.navigationBarHidden = YES;
                
                [self presentViewController:nvc animated:YES completion:nil];
                
            }]];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }]];
            [self.view.window.rootViewController presentViewController:alerVC animated:YES completion:nil];
            
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录是否登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        return NO;
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = (int)buttonIndex;
    if (i == 0) {
        
    }
    else if(i == 1)
    {
        LoginViewController * loginVC = [[LoginViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
        nvc.navigationBarHidden = YES;
        
        [self presentViewController:nvc animated:YES completion:nil];
    }
}
#pragma mark - _tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return questionArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[answerArr objectAtIndex:section] count];;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    AnswerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AnswerTableViewCell"];
    cell.flag = [[selectedArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    CompanySelfCheckOneModel * model = [[answerArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSArray * arr = model.answerArr;
    cell.firstLab.text = [arr objectAtIndex:indexPath.row];

//    if (indexPath.row == 0) {
//        cell.firstLab.text = [arr objectAtIndex:0];
//    }
//    else if (indexPath.row == 1)
//    {
//        cell.firstLab.text = [arr objectAtIndex:1];
//    }
//    else if (indexPath.row == 2)
//    {
//        cell.firstLab.text = [arr objectAtIndex:2];
//    }
//    else if (indexPath.row == 3)
//    {
//        cell.firstLab.text = [arr objectAtIndex:3];
//    }
//    else if (indexPath.row == 4)
//    {
//        cell.firstLab.text = [arr objectAtIndex:4];
//    }
//    else if (indexPath.row == 5)
//    {
//        cell.firstLab.text = model.answer6;
//    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray * mArr = [[NSMutableArray alloc]init];
    CompanySelfCheckOneModel * model = [[answerArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if ([model.type isEqualToString:@"1"]) {
        for (int i = 0; i<model.answerArr.count; i++) {
            if (indexPath.row == i) {
                [mArr addObject:@"1"];
            }
            else
            {
                [mArr addObject:@"0"];
            }
        }
        [selectedArr replaceObjectAtIndex:indexPath.section withObject:mArr];
        [_tableView reloadData];
    }
    else
    {
        NSMutableArray * mArr2 = [selectedArr objectAtIndex:indexPath.section];

        for (int i = 0; i<model.answerArr.count; i++) {
//            if (indexPath.row == i) {
//                [mArr addObject:@"1"];
//            }
//            else
//            {
//                [mArr addObject:@"0"];
//            }
//            NSString * s = [[selectedArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
//            if ([s isEqualToString:@"1"]) {
//                [mArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
//            }
//            else
//            {
//                [mArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
//            }
            for (int i = 0; i<mArr2.count; i++) {
                NSString * s = [mArr2 objectAtIndex:indexPath.row];
                if ([s isEqualToString:@"1"]) {
                    [mArr2 replaceObjectAtIndex:indexPath.row withObject:@"0"];
                }
                else
                {
                    [mArr2 replaceObjectAtIndex:indexPath.row withObject:@"1"];
                }
            }
        }
        [selectedArr replaceObjectAtIndex:indexPath.section withObject:mArr2];
        [_tableView reloadData];
        
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [self createSectionViewWithSection:(int)section];
}
#pragma mark - createSectionView
-(UIView *)createSectionViewWithSection:(int)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    view.backgroundColor = [UIColor whiteColor];
    
    CompanySelfCheckOneModel * model = questionArr[section];
    UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(SIZETO6W(15), 0, SCREEN_WIDTH-SIZETO6W(15)*2, view.height)];
//    lab.text = [NSString stringWithFormat:@"%i. %@",section+1,model.question];
    lab.text = model.question;

    lab.textColor = UIColorFromRGB(0x333944);
    lab.font = [UIFont systemFontOfSize:16];
    [view addSubview:lab];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}
#pragma mark - createtableViewFooterView
-(UIView *)createtableViewFooterView
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150+SIZETO6H(44)+47+30)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    
    UIView * subV = [[UIView alloc]initWithFrame:CGRectMake(SIZETO6W(15), SIZETO6W(15), SCREEN_WIDTH-SIZETO6W(15)*2, 150)];
    subV.layer.masksToBounds = YES;
    subV.layer.borderColor = [UIColorFromRGB(0x94999f) CGColor];
    subV.layer.borderWidth = 1.0f;
    [view addSubview:subV];
    
    //textView
    UITextView * textview = [[UITextView alloc]initWithFrame:CGRectMake(SIZETO6W(15), SIZETO6W(15), subV.width-SIZETO6W(15)*2, subV.height-SIZETO6W(15)*2)];
    textview.delegate = self;
    textview.tag = 712;
    [subV addSubview:textview];
    
    UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 120, 20)];
    lab.text = @"其它的建议";
    lab.tag = 504;
    lab.textColor = UIColorFromRGB(0xdddddd);
    [textview addSubview:lab];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(SIZETO6W(30), subV.bottom+SIZETO6H(44), SCREEN_WIDTH-SIZETO6W(30)*2, 47);
    [btn setBackgroundColor:UIColorFromRGB(0x6EC844)];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 20;
    [btn setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [view addGestureRecognizer:tap];
    
    return view;
}
-(void)btnAction:(UIButton *)btn
{
    NSMutableArray * mArr = [[NSMutableArray alloc]init];
    for (int i=0; i<answerArr.count; i++) {
        CompanySelfCheckOneModel * model = questionArr[i];
        NSArray * arr = selectedArr[i];

        if ([model.type isEqualToString:@"4"]) {
            NSMutableString * mStr = [[NSMutableString alloc]init];
            for (int j = 0; j<arr.count; j++) {
                if ([arr[j] isEqualToString:@"1"]) {
                    if (j == 0) {
                        [mStr appendString:@"A"];
                    }
                    else if (j == 1)
                    {
                        [mStr appendString:@"|B"];
                    }
                    else if (j == 2)
                    {
                        [mStr appendString:@"|C"];
                    }
                    else if (j == 3)
                    {
                        [mStr appendString:@"|D"];
                    }
                    else if (j == 4)
                    {
                        [mStr appendString:@"|E"];
                    }
                    else if (j == 5)
                    {
                        [mStr appendString:@"|F"];
                    }
                    else
                    {
                        [mStr appendString:@"|G"];
                    }
                    NSRange range = [[mStr substringToIndex:1] rangeOfString:@"|"];
                    if (range.location != NSNotFound) {
                        NSString * ss = [mStr substringFromIndex:1];
                        mStr = [[NSMutableString alloc]initWithString:ss];
                    }
                }
                else
                {
                    
                }

            }
            if (![mStr isEqualToString:@""]) {
                NSDictionary * dic = @{model.qid:mStr};
                
                [mArr addObject:dic];
            }
            

        }
        else
        {
            for (int j = 0; j<arr.count; j++) {
                if ([arr[j] isEqualToString:@"1"]) {
                    NSString * str = nil;
                    if (j == 0) {
                        str = @"A";
                    }
                    else if (j == 1)
                    {
                        str = @"B";
                    }
                    else if (j == 2)
                    {
                        str = @"C";
                    }
                    else if (j == 3)
                    {
                        str = @"D";
                    }
                    else if (j == 4)
                    {
                        str = @"E";
                    }
                    else if (j == 5)
                    {
                        str = @"F";
                    }
                    else
                    {
                        str  = @"G";
                    }
                    NSDictionary * dic = @{model.qid:str};
                    [mArr addObject:dic];
                }
                else
                {
                    
                }
            }
        }

    }
    
    UITextView * textView = (UITextView *)[self.view viewWithTag:712];
    [textView resignFirstResponder];
    

    if (mArr.count == answerArr.count) {
        
        
//        for (int i = 0; i<mArr.count; i++) {
//            NSDictionary * d = mArr[i];
//            if (i == 0) {
//                [S appendString:[NSString stringWithFormat:@"{\"%@\":\"%@\"",d.allKeys,d.allValues]];
//            }
//            if (i == mArr.count-1) {
//                [S appendString:[NSString stringWithFormat:@",\"%@\":\"%@\"}",d.allKeys,d.allValues]];
//            }
//            [S appendString:[NSString stringWithFormat:@",\"%@\":\"%@\"",d.allKeys,d.allValues]];
//        }
//        
//        NSData * resData = [[NSData alloc]initWithData:[S dataUsingEncoding:NSUTF8StringEncoding]];
//        NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
        NSMutableDictionary * mDic = [[NSMutableDictionary alloc]init];
        for (int i = 0; i<mArr.count; i++) {
            NSDictionary * dic = mArr[i];
            [mDic setObject:dic.allValues.firstObject forKey:dic.allKeys.firstObject];
        }
        
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString * json = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        [self subAnswerWithArr:json andSuggest:textView.text];
    }
    else
    {
        [Singleton alerSendMessage:@"请做完提交"];
    }
    
    
}
-(void)textViewDidChange:(UITextView *)textView
{
    UILabel * lab = (UILabel *)[self.view viewWithTag:504];
    if ([textView.text isEqualToString:@""]) {
        lab.hidden = NO;
    }
    else
    {
        if (lab.hidden == YES) {
            
        }
        else
        {
            lab.hidden = YES;
        }
    }
    
}
#pragma mark - 获取键盘动态高度
- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
//    [UIView animateWithDuration:0.05 animations:^{
//        _tableView.frame = CGRectMake(0, -keyboardSize.height+64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
//
//    } completion:nil];
    NSLog(@"keyBoard:%f", keyboardSize.height);  //216
    ///keyboardWasShown = YES;
    // 获取键盘动画时间
    CGFloat animationTime  = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        _tableView.transform = CGAffineTransformMakeTranslation(0, - keyboardSize.height);
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }

}
- (void) keyboardWasHidden:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
//    [UIView animateWithDuration:0.1 animations:^{
//        _tableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
//
//    } completion:nil];

    // keyboardWasShown = NO;
    CGFloat animationTime  = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        _tableView.transform = CGAffineTransformIdentity;
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }

}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    UITextView * textView = (UITextView *)[self.view viewWithTag:712];
    [textView resignFirstResponder];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    NSLog(@"touch");
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UITextView * textView = (UITextView *)[self.view viewWithTag:712];
    [textView resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
